package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.article.feign.ApAuthorFeign;
import com.itheima.article.pojo.ApAuthor;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.user.dto.ApUserRealnamePageRequestDto;
import com.itheima.user.mapper.ApUserMapper;
import com.itheima.user.pojo.ApUser;
import com.itheima.user.pojo.ApUserRealname;
import com.itheima.user.mapper.ApUserRealnameMapper;
import com.itheima.user.service.ApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.wemedia.feign.WmUserFeign;
import com.itheima.wemedia.pojo.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @description <p>APP实名认证信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.user.service.impl
 */
@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private WmUserFeign wmUserFeign;

    @Autowired
    private ApAuthorFeign apAuthorFeign;

    @Override
    public PageResultVo<ApUserRealname> findpage(ApUserRealnamePageRequestDto dto) {
        //1.创建page对象
        IPage<ApUserRealname> page = new Page<ApUserRealname>(dto.getPage(), dto.getSize());
        //2.创建wrapper对象
        //2.1设置查询分页条件
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null != dto.getStatus(),ApUserRealname::getStatus,dto.getStatus());
        //3.查询
        page(page,wrapper);
        //4.封装返回
        return PageResultVo.pageResult(dto.getPage(),dto.getSize(),page.getTotal(),page.getRecords());
    }

    @Override
    public void authpass(Map<String, Object> map) {
        //====实名认证
        //0.获取id
        Integer id =(Integer)map.get("id");
        //1.状态判断
        ApUserRealname apUser = getById(id);
        if (null == apUser.getStatus() && apUser.getStatus() !=1){
            throw new LeadNewsException("状态不正确或数据不存在");
        }
        //2.设置实名认证表
        apUser.setId(id.longValue());
        apUser.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_PASS);
        apUser.setUpdatedTime(LocalDateTime.now());

        updateById(apUser);
        Long userId = apUser.getUserId();
        //====用户微服务
        //3.创建pojo
        ApUser user = new ApUser();
        //4.设置用户信息表
        user.setId(userId);
        user.setFlag(BusinessConstants.ApUserConstants.FLAG_WEMEDIA);
        user.setIsIdentityAuthentication(BusinessConstants.ApUserConstants.AUTHENTICATED);

        apUserMapper.updateById(user);
        //=====自媒体微服务
        ResultVo<WmUser> getByIdWmUser = wmUserFeign.getByAppUserId(userId);
        if (!getByIdWmUser.isSuccess()){
            throw new LeadNewsException("查询自媒体用户信息失败");
        }

        ApUser apUser1 = apUserMapper.selectById(userId);

        WmUser wmUser = getByIdWmUser.getData();
        if (null==wmUser){
            wmUser=addWmUser(apUser1);
        }

        Long wmUserId = wmUser.getId();
        //文章微服务
        ResultVo<ApAuthor> byApUserIdWmUserId = apAuthorFeign.getByApUserIdWmUserId(userId, wmUserId);
        if(!byApUserIdWmUserId.isSuccess()){
            log.error("用户实名认证::远程调用文章微服查询失败:{},{},{}",userId,wmUserId,byApUserIdWmUserId.getErrorMessage());
            // 远程调用失败了
            throw new LeadNewsException("查询作者信息失败!");
        }
        ApAuthor data = byApUserIdWmUserId.getData();
        if (null == data){
            addAuAthor(apUser1,wmUserId);
        }

    }

    /**
     * 驳回
     * @param map
     */
    @Override
    public void authfail(Map<String, Object> map) {
        Integer keyId = (Integer) map.get("id");
        String reason = (String) map.get("msg");
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(keyId.longValue());
        apUserRealname.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_REJECT);
        apUserRealname.setUpdatedTime(LocalDateTime.now());
        apUserRealname.setReason(reason);

        updateById(apUserRealname);
    }

    private void addAuAthor(ApUser apUser1, Long wmUserId) {
        ApAuthor apAuthor = new ApAuthor();
        apAuthor.setCreatedTime(LocalDateTime.now());
        apAuthor.setUserId(apUser1.getId());
        apAuthor.setWmUserId(wmUserId);
        apAuthor.setName(apUser1.getName());
        apAuthor.setType(BusinessConstants.ApAuthorConstants.A_MEDIA_USER);
        ResultVo resultVo = apAuthorFeign.add(apAuthor);
        if(!resultVo.isSuccess()){
            log.error("用户实名认证::远程调用添加作者失败:{},{}",apUser1.getId(),wmUserId,resultVo.getErrorMessage());
            throw new LeadNewsException("添加作者失败!");
        }

    }

    private WmUser addWmUser(ApUser apUser1) {
        WmUser wmUser = new WmUser();
        Long aLong = apUser1.getId();

        BeanUtils.copyProperties(apUser1,wmUser);

        wmUser.setId(null);
        wmUser.setApUserId(aLong);
        wmUser.setNickname(wmUser.getName());
        wmUser.setStatus(BusinessConstants.WmUserConstants.TYPE_PERSONAL);
        wmUser.setStatus(BusinessConstants.WmUserConstants.STATUS_OK);
        wmUser.setScore(0);
        wmUser.setCreatedTime(LocalDateTime.now());

        ResultVo<WmUser> wmUserResultVo = wmUserFeign.add(wmUser);
        if(!wmUserResultVo.isSuccess()){
            log.error("用户实名认证::远程调用自媒体添加账号失败:{},{}",aLong,wmUserResultVo.getErrorMessage());
            throw new LeadNewsException("添加自媒体账号失败!");
        }
        return wmUserResultVo.getData();


    }


}
